<?php
/**
 * 本地榜单沉淀名单控制器
 */
namespace Beerus\Modules\LocalRank\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DecoCompany as mDecoCompany;
use Doraemon\model\Designer as mDesigner;
use Doraemon\model\Member as mMember;
use Doraemon\service\Member as sMember;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\LocalRank\LocalRankBlack as mLocalRankBlack;
use Illuminate\Support\MessageBag;
use Doraemon\pockets\constInterface\LocalRank as iLocalRank;

class LocalRankBlackController extends Controller {
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content) {
        $page = $request->get('page', 1);
        $pageSize = $request->get('per_page', self::PAGE_SIZE);
        $uid = $request->get('uid', 0);
        $nick = $request->get('nick', '');
        $condition = [];
        if (!empty($uid)) {
            $condition['uid'] = $uid;
        }
        if (!empty($nick)) {
            $uid = mMember::getUidByNick($nick);
            $condition['uid'] = !empty($uid) ? $uid : 0;
        }
        $condition['data_status'] = mLocalRankBlack::STATUS_NORMAL;
        $total = mLocalRankBlack::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = mLocalRankBlack::select('*', $condition);
        $uids = array_column($list, 'uid');
        $memberList = sMember::getUserInfoByUserIds($uids);
        $designerUids = $decoUids = [];
        if (!empty($memberList)) {
            foreach ($memberList as $memberItem) {
                if ($memberItem['type'] == mMember::AUTH_USER_DESIGNER) {
                    $designerUids[] = $memberItem['uid'];
                } else {
                    $decoUids[] = $memberItem['uid'];
                }
            }
        }
        // 获取设计师信息
        $designerUidInfoMap = [];
        if (!empty($designerUids)) {
            $designerList = mDesigner::getDesignerByIds($designerUids);
            $designerUidInfoMap = array_column($designerList, null, 'uid');
        }
        // 获取装修公司信息
        $decoUidInfoMap = [];
        if (!empty($decoUids)) {
            $decoList = mDecoCompany::getListByUids($decoUids);
            $decoUidInfoMap = array_column($decoList, null, 'uid');
        }
        // 获取设计师的信息
        foreach ($list as &$item) {
            $item['nick'] = $memberList[$item['uid']]['nick'] ?? '';
            $item['user_type'] = $memberList[$item['uid']]['type'] ? mMember::$typeDesc[$memberList[$item['uid']]['type']] : '';
            if (in_array($item['uid'], $designerUids)) {
                $item['main_area'] = $designerUidInfoMap[$item['uid']]['main_area_name'];
            } else {
                $item['main_area'] = $decoUidInfoMap[$item['uid']]['main_area_name'];
            }
            $item['add_time'] = date('Y-m-d H:i:s', $item['edit_time']);
        }

        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(6, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入用户uid');
                    });
                    $filter->column(6, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入用户昵称');
                    });
                    $filter->expand();
                });

                $grid->column('id', 'ID');
                $grid->column('uid', '用户UID');
                $grid->column('nick', '用户昵称');
                $grid->column('user_type', '用户身份');
                $grid->column('main_area', '主要服务地区');
                $grid->column('add_time', '创建时间');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            }
        );
        return $content
            ->header('本地榜单沉淀名单列表')
            ->row($gridList);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        if (!empty($id)) {
            $data = mLocalRankBlack::getInfoById($id);
            $isCreate = false;
        } else {
            $data = [];
            $isCreate = true;
        }
        $form = new Form($data);


        if (!empty($id)) {
            $form->text('id', 'ID')->readOnly();
        }
        $form->text('uid', '用户UID')->required();
        $form->select('list_type', '榜单类型')
            ->options([iLocalRank::LIST_TYPE_PUBLIC_PRAISE => '口碑榜'])
            ->default(iLocalRank::LIST_TYPE_PUBLIC_PRAISE)
            ->required();

        $form->confirm('确定提交吗？');
        $form->action('/admin/LocalRank/black/save');

        $header = '沉淀名单'.($isCreate ? '新增' : '修改');
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '沉淀名单列表', 'url' => '/LocalRank/black'],
                ['text' => $header],
            )->row($tab);
    }

    public function save(Request $request) {
        $uid = $request->input('uid');
        $listType = $request->input('list_type');
        // uid是否存在判断
        if (!mMember::getUserInfo($uid)) {
            $error = new MessageBag(['title' => '用户不存在']);
            return back()->with(compact('error'));
        }
        if (!in_array($listType, [iLocalRank::LIST_TYPE_PUBLIC_PRAISE])) {
            $error = new MessageBag(['title' => '该榜单类型不存在']);
            return back()->with(compact('error'));
        }
        $blackInfo = mLocalRankBlack::getInfoByUidAndListType($uid, $listType);
        if (!empty($blackInfo) && $blackInfo['data_status'] == mLocalRankBlack::STATUS_NORMAL) {
            $error = new MessageBag(['title' => '该用户已在沉淀名单中']);
            return back()->with(compact('error'));
        }
        if (!empty($blackInfo) && $blackInfo['data_status'] == mLocalRankBlack::STATUS_DELETE) {
            // 更新
            $updateData = [
                'data_status' => mLocalRankBlack::STATUS_NORMAL,
                'edit_time' => time(),
                'admin_id' => Admin::user()->id
            ];
            if (!mLocalRankBlack::dataUpdate($updateData, ['uid' => $uid, 'list_type' => $listType])) {
                $error = new MessageBag(['title' => '沉淀用户添加失败']);
                return back()->with(compact('error'));
            }
        } else {
            // 新增
            $addData = [
                'uid' => $uid,
                'list_type' => $listType,
                'data_status' => mLocalRankBlack::STATUS_NORMAL,
                'add_time' => time(),
                'edit_time' => time(),
                'admin_id' => Admin::user()->id
            ];
            if (!mLocalRankBlack::dataInsert($addData)) {
                $error = new MessageBag(['title' => '新增沉淀用户失败']);
                return back()->with(compact('error'));
            }
        }
        $success = new MessageBag(['title' => '添加成功']);
        return redirect('/admin/LocalRank/black')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $blackUser = mLocalRankBlack::getInfoById($id);
        if ($blackUser) {
            // 更新
            $updateData = [
                'data_status' => mLocalRankBlack::STATUS_DELETE,
                'edit_time' => time(),
                'admin_id' => Admin::user()->id
            ];
            if (!mLocalRankBlack::dataUpdate($updateData, ['id' => $id])) {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "该沉淀用户不存在",
            ]);
        }
    }
}
